var router = require('express').Router(),
  model = require('../models/model');
var formidable = require("formidable");
var fs = require("fs");

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index')
});
// router.get('/login', function(req, res, next) {
//   res.render('./author/login')
// });
// router.get('/register', function(req, res, next) {
//   res.render('./author/login')
// });

router.get('/upload', function(req, res, next) {
  res.render('upload')
});

/// ok
/**

router.post('/upload', function(req, res) {
  var form = new formidable.IncomingForm();
  console.log("about to parse");
  form.uploadDir='app/public/tmp'
  form.keepExtensions = true;//保存扩展名
  form.parse(req, function(error, fields, files) {
    console.log("fieldsfieldsfields:")
    console.log(files)
    var filename = files.upload.name;
    var size = files.upload.size;

    // 名称，大小写入文件
    var obj = {
      filename: filename,
      filesize: size
    }
    var json = JSON.stringify(obj);
    fs.writeFile('app/public/imgInfo/img.json', json, 'utf8', function(err) {
      if (err)
        throw err;
      }
    );

    //保存图片到upload文件夹
    fs.writeFileSync("app/public/uploads/" + filename, fs.readFileSync(files.upload.path));
    fs.watch("app/public/uploads/" + filename,function(data){
      console.log(data)
    })
    if (error) {
      console.log(error)
    } else {
      res.redirect('/upload');
    }
  });
});
*/
router.post('/upload', function(req, res) {
  var form = new formidable.IncomingForm();
  form.encoding = 'utf-8'; //设置编辑
  form.keepExtensions = true; //保留后缀
  var files={};
  form.on('file', function(field, file) { //上传文件
     files=file
  }).on('end', function() {
    fs.rename(files.path, 'app/public/uploads/'+files.name, function(err) {
      if (err)
        throw err;
      fs.stat('app/public/uploads/'+files.name, function(err, stats) {
        if (err)
          throw err;
          if(stats.size==files.size){
            console.log('完成传输了')

          //  名称，大小写入文件
            var obj = {
              filename: files.name,
              filesize: files.size,
              status:'ok'
            }
            var json = JSON.stringify(obj);
            fs.writeFile('app/public/imgInfo/img.json', json, 'utf8', function(err) {
              if (err)
                throw err;
              console.log('写入成功');
              res.redirect('/upload');
              });
          }else{
            console.log('没完成传输');
          }
      });
    })
  })
  form.parse(req);
});

module.exports = router;
